﻿using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.IO;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Web;
using System.Net.Mail;
using System.Net;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
namespace BLL
{
    public class CommonBLL
    {
        public static string TotalCode = "0";
        public static string PrefixSpecialSite = "dlpsite";
        public static string SiteID = "1";
        public static string MainTitle = DAL.EnvInfo.MainTitle;
        #region SetPermissionColumns
        public static void SetPermissionColumns(GridView MyGrid, string mod)
        {
            
            if (MyGrid.Columns.Count > 0)
            {
                MyGrid.Columns[MyGrid.Columns.Count - 1].Visible = new CmsBLL().HasPermissionDelete(mod);
                MyGrid.Columns[MyGrid.Columns.Count - 2].Visible = new CmsBLL().HasPermissionEdit(mod);
            }
        }

        public static void SetPermissionColumns(Literal literal, string mod)
        {

            literal.Visible = new CmsBLL().HasPermissionDelete(mod);           
        }

        #endregion
        #region ExportDataFromDataTable-GridToExcel,Word,Pdf
        /// <summary>
        /// Xuất dữ liệu từ GridView ra word
        /// </summary>
        private void XuatDuLieuRaWord(GridView MyGridview)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.doc");
            HttpContext.Current.Response.Charset = "";
            HttpContext.Current.Response.ContentType = "application/vnd.ms-word ";
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            // Bỏ phân trang - Nếu chỉ muỗn Export Trang hiện hành thì chọn =true
            MyGridview.AllowPaging = false;
            MyGridview.DataBind();
            MyGridview.RenderControl(hw);
            HttpContext.Current.Response.Output.Write(sw.ToString());
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }
        /// <summary>
        /// Xuất dữ liệu từ GridView ra Excel
        /// </summary>
        private void XuatDuLieuRaExcel(GridView MyGridview)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.AddHeader("content-disposition",
             "attachment;filename=GridViewExport.xls");
            HttpContext.Current.Response.Charset = "";
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            // Bỏ phân trang - Nếu chỉ muỗn Export Trang hiện hành thì chọn =true
            MyGridview.AllowPaging = false;
            MyGridview.DataBind();
            MyGridview.RenderControl(hw);
            //Thay đổi Style
            string style = @"";
            HttpContext.Current.Response.Write(style);
            HttpContext.Current.Response.Output.Write(sw.ToString());
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }
        /// <summary>
        /// Hàm xuất dữ liệu từ gridview ra pdf
        /// </summary>
        private void XuatDuLieuGridRaPDF(GridView MyGridview)
        {
            HttpContext.Current.Response.ContentType = "application/pdf";
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
            HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            MyGridview.AllowPaging = false;
            MyGridview.DataBind();
            MyGridview.RenderControl(hw);
            StringReader sr = new StringReader(sw.ToString());
            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            PdfWriter.GetInstance(pdfDoc, HttpContext.Current.Response.OutputStream);
            pdfDoc.Open();
            htmlparser.Parse(sr);
            pdfDoc.Close();
            HttpContext.Current.Response.Write(pdfDoc);
            HttpContext.Current.Response.End();
        }
        #endregion
        #region MethodSendMail
        public void SendMailUTF8(string To, string Title, string Body)
        {
            SmtpClient SmtpServer = new SmtpClient();
            SmtpServer.Credentials = new System.Net.NetworkCredential("phamtam34@gmail.com", "pvt@mk2a");
            SmtpServer.Port = 587;
            SmtpServer.Host = "smtp.gmail.com";
            SmtpServer.EnableSsl = true;
            MailMessage mail = new MailMessage();
            String[] addr = To.Split(',');
            mail.From = new MailAddress("phamtam34@gmail.com", "http://dongly.com.vn/", System.Text.Encoding.UTF8);
            Byte i;
            for (i = 0; i < addr.Length; i++)
                mail.To.Add(addr[i]);
            mail.Subject = Title;
            mail.IsBodyHtml = true;
            mail.Body = Body;
            mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
            mail.ReplyTo = new MailAddress(To);
            SmtpServer.Send(mail);                            
        }
        public void SendMail(string To, string Title, string Body)
        {
            var fromAddress = new MailAddress("phamtam34@gmail.com", "http://dongly.com.vn/");
            var toAddress = new MailAddress(To);
            string fromPassword = "pvt@mk2a";
            string subject = Title;
            string body = Body;

            var smtp = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
                Timeout = 20000
            };
            using (var message = new MailMessage(fromAddress, toAddress)
            {
                Subject = subject,
                Body = body
            })
            {
                smtp.Send(message);
            }
        }
        #endregion
        public void LoadDropDonwList(DropDownList ddlName, DataTable dtbName, string strFieldText, string strFieldValue)
        {
            ddlName.DataSource = dtbName;
            ddlName.DataTextField = strFieldText;
            ddlName.DataValueField = strFieldValue;
            ddlName.DataBind();
        }
        public void LoadCombobox(DropDownList cboName, DataTable dtbName, string strFieldText, string strFieldValue, string ValueDefault, string TextDefault)
        {
            System.Web.UI.WebControls.ListItem item = new System.Web.UI.WebControls.ListItem();
            cboName.Items.Clear();
            cboName.Items.Add(item);
            item.Selected = true;
            item.Value = ValueDefault;
            item.Text = TextDefault;
        }
        public static void RegisterCKFinder(CKEditor.NET.CKEditorControl CKEditorControl)
        {
            CKFinder.FileBrowser _FileBrowser = new CKFinder.FileBrowser();
            _FileBrowser.BasePath = "" + DAL.EnvInfo.FolderRoot + "ckfinder/";
            _FileBrowser.SetupCKEditor(CKEditorControl);   
        }
        public static void UploadImageToSmallImage(string filename, Stream ContenLength, int MaxWidth, int MaxHeight)
        {
            try
            {
                string filepathsmallimage = HttpContext.Current.Server.MapPath("" + DAL.EnvInfo.PathUpload + "smallimages//") + filename;
                Bitmap uploadedImage = new Bitmap(ContenLength);

                // Set the maximum width and height here.
                // You can make this versatile by getting these values from
                // QueryString or textboxes
                int maxWidth = MaxHeight;
                int maxHeight = MaxHeight;

                // Resize the image
                Bitmap resizedImage = GetScaledPicture(uploadedImage, maxWidth, maxHeight);

                //Save the image
                // String virtualPath = "~/temp/" + System.Guid.NewGuid().ToString() + "." + ext;
                //String tempFileName = Server.MapPath(virtualPath);
                resizedImage.Save(filepathsmallimage, uploadedImage.RawFormat);
            }
            catch (Exception)
            {
                
                throw;
            }
        }
        public static string UploadMultiImageToServer(System.Web.UI.WebControls.FileUpload FileUploadControl, bool savesmall, bool savelarge)
        {
            string RetValue = string.Empty;
            if (FileUploadControl.HasFile)
            {
                string strFileName = FileUploadControl.FileName;
                try
                {
                    Stream fStream = FileUploadControl.FileContent;
                    strFileName = FileUploadControl.FileName.Replace(' ', '_');
                    strFileName = strFileName.Substring(strFileName.LastIndexOf("\\") + 1);
                    strFileName = GetFilename(strFileName);

                    string filepathsmallimage = HttpContext.Current.Server.MapPath("" + DAL.EnvInfo.PathUpload + "smallimages//") + strFileName;
                    string filepathlargeimage = HttpContext.Current.Server.MapPath("" + DAL.EnvInfo.PathUpload + "images//") + strFileName;

                    // Validate the uploaded file
                    // 1. The uploaded file should not be a blank file
                    if (FileUploadControl.FileBytes.Length == 0)
                    {
                        //lblMessage.Text = "File bạn chọn bị lỗi! dung lượng file = " + FileUploadBanner.FileBytes.Length.ToString() + " bytes";
                        RetValue = "ERROR! " + "File bạn chọn bị lỗi! dung lượng file = " + FileUploadControl.FileBytes.Length.ToString() + " bytes";
                    }
                    // 2. The uploaded file should be having one of the allowed extensions
                    string ext = System.IO.Path.GetExtension(FileUploadControl.FileName).TrimStart(".".ToCharArray()).ToLower();
                    if ((ext != "jpeg") && (ext != "jpg") && (ext != "png") && (ext != "gif") && (ext != "bmp") && (ext != "swf"))
                    {
                        //lblMessage.Text = "Định dạng file bạn chọn không hợp lệ (File hợp lệ dạng Ảnh hoặc Flash)";
                        RetValue = "ERROR! " + "Định dạng file bạn chọn không hợp lệ (File hợp lệ dạng Ảnh hoặc Flash)";
                    }
                    RetValue = strFileName;
                    // Validation successful
                    // Load the image into Bitmap Object
                    if (savesmall)
                    {
                        Bitmap uploadedImage = new Bitmap(FileUploadControl.FileContent);

                        // Set the maximum width and height here.
                        // You can make this versatile by getting these values from
                        // QueryString or textboxes
                        int maxWidth = 170;
                        int maxHeight = 160;

                        // Resize the image
                        Bitmap resizedImage = GetScaledPicture(uploadedImage, maxWidth, maxHeight);

                        //Save the image
                        // String virtualPath = "~/temp/" + System.Guid.NewGuid().ToString() + "." + ext;
                        //String tempFileName = Server.MapPath(virtualPath);
                        resizedImage.Save(filepathsmallimage, uploadedImage.RawFormat);
                    }
                    if (savelarge)
                        FileUploadControl.SaveAs(filepathlargeimage);
                }
                catch (Exception ex)
                {
                    RetValue = "ERROR! " + ex.Message.ToString();
                }
            }           
            return RetValue;
        }
        #region StringRegex
        public static string PatternRequiteUrl = @"((.*).html$|(.*).aspx$)";
        public static string PatternProductDetail = @"/([0-9]+)/c([0-9]+)_p([\w\-]*)/.([^\.]*).html$";
        public static string PatternProductByCategory = @"/([0-9]+)/c([0-9]+)/.([^\.]*).html$";
        public static string PatternNewsDetail = @"/([0-9]+)/g([0-9]+)_n([0-9]+)/.([^\.]*).html$";
        public static string PatternNewsByCategory = @"/([0-9]+)/g([0-9]+)/.([^\.]*).html$";
        public static string PatternStaticNews = @"(.*)/s([0-9]+)/.([^\.]*).html$";
        public static string PatternUrlCart = @"((.*)cart.html$|(.*)cart.aspx$)";
        public static string PatternUrlContacForm = @"(.*)lien-he.html$";
        public static string PatternRedirectDefaultPage = @"((.*)/home/$|(.*)home.html$)";
        public static string PatternSearch = @"/([0-9]+)/search/(.*).html$";

        public static string[] GetValueGroupFromStringByPattern(string input, string pattern)
        {
            string[] retVal = null;
            try
            {
                Match match = Regex.Match(input, pattern, RegexOptions.IgnoreCase);
                if (match.Groups.Count > 0)
                {
                    retVal = new string[match.Groups.Count];
                    for (int i = 0; i < match.Groups.Count; i++)
                    {
                        retVal[i] = match.Groups[i].Value;
                    }
                }
                return retVal;
            }
            catch (Exception)
            {
                return retVal;
            }
        }
        public static bool CheckPattern(string input, string pattern)
        {
            try
            {
                Match match = Regex.Match(input, pattern, RegexOptions.IgnoreCase);
                if (match.Success)
                {
                    return true;
                }
                else
                    return false;
            }
            catch (Exception)
            {
                return false;
            }
        }
        #endregion
        #region Handler Image
        public static Bitmap GetScaledPicture(Bitmap source, int maxWidth, int maxHeight)
        {
            int width, height;
            float aspectRatio = (float)source.Width / (float)source.Height;

            if ((maxHeight > 0) && (maxWidth > 0))
            {
                if ((source.Width < maxWidth) && (source.Height < maxHeight))
                {
                    //Return unchanged image
                    return source;
                }
                else if (aspectRatio > 1)
                {
                    // Calculated width and height,
                    // and recalcuate if the height exceeds maxHeight
                    width = maxWidth;
                    height = (int)(width / aspectRatio);
                    if (height > maxHeight)
                    {
                        height = maxHeight;
                        width = (int)(height * aspectRatio);
                    }
                }
                else
                {
                    // Calculated width and height,
                    // and recalcuate if the width exceeds maxWidth
                    height = maxHeight;
                    width = (int)(height * aspectRatio);
                    if (width > maxWidth)
                    {
                        width = maxWidth;
                        height = (int)(width / aspectRatio);
                    }
                }
            }
            else if ((maxHeight == 0) && (source.Width > maxWidth))
            {
                // If MaxHeight is not provided (unlimited), and
                // the source width exceeds maxWidth,
                // then recalculate height
                width = maxWidth;
                height = (int)(width / aspectRatio);
            }
            else if ((maxWidth == 0) && (source.Height > maxHeight))
            {
                // If MaxWidth is not provided (unlimited), and the
                // source height exceeds maxHeight, then
                // recalculate width
                height = maxHeight;
                width = (int)(height * aspectRatio);
            }
            else
            {
                //Return unchanged image
                return source;
            }

            Bitmap newImage = GetResizedImage(source, width, height);
            return newImage;
        }
        public static Bitmap GetResizedImage(Bitmap source, int width, int height)
        {
            //This function creates the thumbnail image.
            //The logic is to create a blank image and to
            // draw the source image onto it

            Bitmap thumb = new Bitmap(width, height);
            Graphics gr = Graphics.FromImage(thumb);

            gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
            gr.SmoothingMode = SmoothingMode.HighQuality;
            gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
            gr.CompositingQuality = CompositingQuality.HighQuality;

            gr.DrawImage(source, 0, 0, width, height);
            return thumb;
        }
        public static System.Drawing.Image resizeImage(System.Drawing.Image img, int width, int height)
        {
            Bitmap b = new Bitmap(width, height);
            Graphics g = Graphics.FromImage((System.Drawing.Image)b);

            g.InterpolationMode = InterpolationMode.Bicubic;    // Specify here
            g.DrawImage(img, 0, 0, width, height);
            g.Dispose();

            return (System.Drawing.Image)b;
        }
        public static string GetFilename(string filename)
        {
            int pos = filename.LastIndexOf(".");
            string tenfile = filename.Substring(0, pos);
            string morong = filename.Substring(pos + 1, filename.Length - (pos + 1));
            return tenfile + "-" + GetDateTime() + "." + morong;// Replace('.', '_');//file.Url;
        }
        public static string GetDateTime()
        {
            return DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();
        }
        #endregion
        #region RemoveSpecialWord
        private static readonly string[] VietnameseSigns = new string[]
        {

            "aAeEoOuUiIdDyY",

            "áàạảãâấầậẩẫăắằặẳẵ",

            "ÁÀẠẢÃÂẤẦẬẨẪĂẮẰẶẲẴ",

            "éèẹẻẽêếềệểễ",

            "ÉÈẸẺẼÊẾỀỆỂỄ",

            "óòọỏõôốồộổỗơớờợởỡ",

            "ÓÒỌỎÕÔỐỒỘỔỖƠỚỜỢỞỠ",

            "úùụủũưứừựửữ",

            "ÚÙỤỦŨƯỨỪỰỬỮ",

            "íìịỉĩ",

            "ÍÌỊỈĨ",

            "đ",

            "Đ",

            "ýỳỵỷỹ",

            "ÝỲỴỶỸ"
        };
        public static string RemoveSign4VietnameseString(string str)
        {

            //Tiến hành thay thế , lọc bỏ dấu cho chuỗi

            for (int i = 1; i < VietnameseSigns.Length; i++)
            {

                for (int j = 0; j < VietnameseSigns[i].Length; j++)

                    str = str.Replace(VietnameseSigns[i][j], VietnameseSigns[0][i - 1]);
            }
            return str;
        }
        public static string RemoveSpecialWord(string str)
        {
            string sp = @"~!@#$%^&*()+[]{}\/><.,:;";
            int lenght;
            lenght = str.Length;
            string rt = "";
            for (int i = 0; i < lenght; i++)
            {
                bool p = true;
                for (int k = 0; k < sp.Length; k++)
                {
                    if (str[i] == sp[k])
                    {
                        p = false;
                        break;
                    }
                }
                if (p == true) rt = rt + str[i];
            }
            return rt;
        }
        #endregion
        #region Products - GetValueSortOrder
        public static string GetValueSortOrder(string prefix, string SortExpression, string SortDirection)
        {
            string OrderBy = string.Empty;
            if (!string.IsNullOrEmpty(SortExpression) && !string.IsNullOrEmpty(SortDirection))
                if (!string.IsNullOrEmpty(prefix))
                    OrderBy = " " + prefix + "." + SortExpression + " " + SortDirection + " ";
                else
                    OrderBy = " " + SortExpression + " " + SortDirection + " ";
            return OrderBy;
        }
        #endregion
        #region Environment
        public static string RenderEnvironment()
        {
            string prefixUrl = DAL.EnvInfo.HttpRoot;
            StringBuilder Html = new StringBuilder();
            Html.Append(
                "<link rel=\"stylesheet\" href=\"" + prefixUrl + "css/style.css?23042011\" type=\"text/css\" media=\"all\"> \n" +
                "<script src=\"" + prefixUrl + "js/jquery-1.5.2.min.js\" type=\"text/javascript\"></script> \n" +
                "<script src=\"" + prefixUrl + "js/jcarousellite_1.0.1.js\" type=\"text/javascript\"></script> \n" +
                "<script type=\"text/javascript\" language=\"javascript\" src=\"" + prefixUrl + "js/ddsmoothmenu.js\"></script> \n" +
                "<script type=\"text/javascript\" language=\"javascript\" src=\"" + prefixUrl + "js/CmsCommonFrontEnd.js\"></script> \n" +
                "<script type=\"text/javascript\" language=\"javascript\" src=\"" + prefixUrl + "js/scriptcart.js\"></script>" +
                
                "<script type=\"text/javascript\" language=\"javascript\" src=\"" + prefixUrl + "js/CmsPaging.js\"></script>" +
                "<script type=\"text/javascript\" language=\"javascript\" src=\"" + prefixUrl + "js/slimbox2.js\"></script>" +
                "<script type=\"text/javascript\" language=\"javascript\">\n" +
                "    ddsmoothmenu.init({\n" +
                "        mainmenuid: \"mainmenu\", //menu DIV id\n" +
                "        orientation: 'h', //Horizontal or vertical menu: Set to \"h\" or \"v\"\n" +
                "        classname: 'ddsmoothmenu', //class added to menu's outer DIV\n" +
                "        //customtheme: [\"#1c5a80\", \"#18374a\"],\n" +
                "        contentsource: \"markup\" //\"markup\" or [\"container_id\", \"path_to_menu_file\"]\n" +
                "    })\n" +
                "</script>\n" +
                "<script src=\"" + prefixUrl + "js/jquery.vticker-min.js\" type=\"text/javascript\"></script>\n" +
                "<script src=\"" + prefixUrl + "js/jquery.nivo.slider.js\" type=\"text/javascript\"></script>\n" +
                "<script src=\"" + prefixUrl + "js/tooltip.js\" type=\"text/javascript\"></script>\n" +
                "<script type=\"text/javascript\">\n" +
                "    $(function () {\n" +
                "        $('.newsscroll').vTicker({\n" +
                "            speed: 500,\n" +
                "            pause: 3000,\n" +
                "            animation: 'fade',\n" +
                "            mousePause: true,\n" +
                "            showItems: 1\n" +
                "        });\n" +
                "    });\n" +
                "</script>\n" +
                "<script type=\"text/javascript\">\n" +
                "    $(window).load(function () {\n" +
                "        $('#mainslide').nivoSlider({\n" +
                "            slices: 35,\n" +
                "            directionNav: false,\n" +
                "            pauseOnHover: true\n" +
                "        });\n" +
                "    });\n" +
                "</script>\n" +
                "<script type=\"text/javascript\" language=\"javascript\">\n" +
                "    $(function () {\n" +
                "        $(\".slider1\").jCarouselLite({\n" +
                "            auto: 1800,\n" +
                "            btnNext: \".next1\",\n" +
                "            btnPrev: \".prev1\",\n" +
                "            visible: 4,\n" +
                "            hoverPause: true\n" +
                "        });\n" +
                "        $(\".slider2\").jCarouselLite({\n" +
                "            btnNext: \".next2\",\n" +
                "            btnPrev: \".prev2\",\n" +
                "            visible: 8\n" +
                "        });\n" +


                "    });\n" +
                "</script>\n" +
                //"<script type=\"text/javascript\"  language=\"javascript\">\n" +
                //"    $(document).ready(function () {\n" +
                //"        $('a.tips').cluetip();\n" +

                //"        $('#houdini').cluetip({\n" +
                //"            splitTitle: '|', // use the invoking element's title attribute to populate the clueTip...\n" +
                //"            // ...and split the contents into separate divs where there is a \"|\"\n" +
                //"            showTitle: false // hide the clueTip's heading\n" +
                //"        });\n" +
                //"    });\n" +
                //"</script>\n" +
                "<!--[if LTE 8]>\n" +
                "<link rel=\"stylesheet\" href=\"" + prefixUrl + "css/ie.css?23042011\" type=\"text/css\" media=\"all\">\n" +
                "<![endif]-->\n");
            return Html.ToString();
        } 
        #endregion       
        private int RandomNumber(int min, int max)
        {
            Random random = new Random();
            return random.Next(min, max);
        }
        public string RandomNumber()
        {
            string retstr = "<span class=\"clsrandomnumber\">";
            int so1 = RandomNumber(0, 9);
            int so2 = RandomNumber(0, 9);
            retstr += so1.ToString() + " + " + so2.ToString() + " = </span>";
            TotalCode = (so1 + so2).ToString();
            return retstr;
        }
        public string FormatHtml(string val, int limitChar)
        {
            val = new RemoveHtml.Class1().RemoveHTML(val);
            string extend = string.Empty;
            if (val.Length > limitChar)
            {
                val = val.Substring(0, limitChar);
                extend = "...";
            }
            val = val.Replace("\"", "");
            val = val.Replace("\n", "");
            val = val.Replace("\r", "").Trim();
            return val + extend;
        }
        public string FormatHtml(string val)
        {
            val = new RemoveHtml.Class1().RemoveHTML(val);           
            val = val.Replace("\"", "");
            val = val.Replace("\n", "");
            val = val.Replace("\r", "").Trim();
            return val;
        }
    }
}
